package com.eascs.web.o2o.report.service;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.notify.email.EmailSender;
import com.eascs.notify.email.entity.EmailContentEntity;
import com.eascs.web.o2o.report.dao.WorkflowReportDao;
import com.eascs.web.o2o.report.dto.MessageDTO;
import com.eascs.web.o2o.report.dto.MessageReceiver;
import com.eascs.web.o2o.report.util.WebServiceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

@Service("messageService")
public class MessageService{
	private final Logger logger = LoggerFactory.getLogger(MessageService.class);
	
	@Value("${msg.url}")
	private String msgUrl;	//短信接口URL
	
	@Inject
	WebServiceUtil webServiceUtil;
	
	@Autowired
	WorkflowReportDao workflowReportDao;
	
	@Autowired
	private EmailSender emailSender;
	
	public static final String	MSG_TEMPLATE	= "<?xml version=\"1.0\" encoding=\"UTF-8\"?><sms>"
			+ "<messagecontents>%s</messagecontents><sendtype>%s</sendtype>"
			+ "<senddate>%s</senddate><creator>%s</creator>%s</sms>";

	/**
	 * 发送短信
	 * @param msg
	 * @return
	 * 2016年6月22日
	 */
	public boolean sendMsg(MessageDTO msg) {
		List<Object> params = new ArrayList<>();
		params.add(msg.getMsgContent());
		params.add(msg.getSendType().getValue());
		params.add(msg.getSendTime());
		params.add(msg.getSenderName());
		
		List<MessageReceiver> receivers = msg.getReceivers();
		if(CollectionUtils.isEmpty(receivers)){
			throw new RuntimeException("[REPROT][MessageService]消息接收人为空");
		}
		
		StringBuilder receiversStr = new StringBuilder();
		for(MessageReceiver receiver : receivers){
			receiversStr.append("<sendnos><sendno>").append(receiver.getPhone()).
						 append("</sendno><sendname>").append(receiver.getName()).
					     append("</sendname></sendnos>");
		}
		params.add(receiversStr);
		
		String requestContent = String.format(MSG_TEMPLATE, params.toArray());
		
		String result = webServiceUtil.call(msgUrl, "sendSMS", requestContent);
		
		
		if(!result.equals("Y")) {
			String sql="update wf_message set sms_error= ? where message_id=? " ;
		    workflowReportDao.excuteSql(sql,result,msg.getId());//发送短信失败,插入异常信息
			logger.info("发送短信失败,响应消息[{}]", result);

		}
		return result.equals("Y");
	}
	
	/**
	 * 发送邮件
	 * @return
	 * 2016年6月22日
	 */
	public boolean sendEmail(EmailContentEntity entity) {
		boolean flag = false;
		try {
			emailSender.send(entity);
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

}
